<template>
  <!-- 在共享市场  下单使用   -->
  <el-dialog :title="title" :visible.sync="dialogVisible" @close="close" append-to-body :close-on-click-modal="false" width="500px">
    <div class="new_form_box" v-loading="loading">
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="90px" class="demo-ruleForm">
        <el-form-item label="卡位管理方" prop="carrierId">
          <div style="width: 200px;">
            <span v-if="type=='add'">{{guanlifang?guanlifang.chuzufangName:'' }}</span>
            <span v-if="type=='xufei'">{{form.chuzufangName||'' }}</span>
          </div>
        </el-form-item>
        <el-form-item label="游戏运营商" prop="carrierId">
          <div style="width: 200px;">

            <span v-if="type=='add'"> {{ setObj?setObj.carrierName:'' }}</span>
            <span v-if="type=='xufei'">{{form.carrierName||'' }}</span>
          </div>
        </el-form-item>
        <el-form-item label="单价" prop="">
          <div style="width: 200px;">
            {{ setObj?setObj.monthPrice:'' }}元/卡/月
          </div>
        </el-form-item>
        <el-form-item v-if="type=='add'" label="号码数量" prop="num">
          <el-input :disabled="type!='add'" @change="jisuan" style="width:100px" :controls="false" v-model="form.num" placeholder="请输入"></el-input>
          <span style="padding-right: 28px;color: #999;">库存数量: <span>{{this.kexuanNum||'0'}}</span></span>
        </el-form-item>
        <el-form-item v-else label="号码数量" prop="num">
          <span style="display: inline-block;width: 200px;">{{ form.num }}</span>
        </el-form-item>
        <br />
        <el-form-item :label="type=='xufei'?'续费时长':'使用时长'" prop="monthNum">
          <el-input type="number" :min="setObj?setObj.minMonth:1" @change="jisuan" style="width:100px;" v-model="form.monthNum" placeholder="请输入"></el-input>
          <span style="padding-right: 85px;">月</span>
        </el-form-item>
        <div style="color: #999;padding-bottom: 8px;padding-left: 32px;">
          使用时长{{ setObj&&setObj.minMonth?setObj.minMonth:1 }}月起
        </div>
      </el-form>
    </div>

    <div class="price-box flex alc">
      <template>
        <div class="flex alc">
          使用费：
          <span class="price1"> ¥{{ form.shiyongfei||0 }}</span>
        </div>
        <div class="flex alc" v-if="form.fuwufei&&setObj&&setObj.fuwufeiType==2">
          服务费：
          <span class="price1"> ¥{{ form.fuwufei||0 }}</span>
        </div>
        <div class="flex alc">
          应付金额：
          <span class="red">¥ </span> <span class="price"> {{ form.shifu||0 }}</span>
        </div>
      </template>
    </div>
    <div class="price-box yue flex alc">
      <template>
        <div class="flex alc">
          当前余额：
          <span class="price1"> ¥{{ shopInfo.availableMoney||0 }}</span>
        </div>
      </template>
    </div>
    <div v-if="setObj&&setObj.fuwufeiType==2" class="tip">提示：服务费{{fuwufeidanjia}}元/卡/月</div>
    <div v-if="setObj&&setObj.fuwufeiType==2" class="tip">
      按照该卡位管理方设置，卡位共享服务费将由您承担。
    </div>

    <div slot="footer" class="center">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">
        <span v-if="type=='xufei'">确认续费并支付</span>
        <span v-else>使用并支付</span>
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import phoneApi from "@/api/phoneManage";
import selectBtnVue from "../../../components/select-btn.vue";
export default {
  name: "",
  components: { selectBtnVue },
  data() {
    return {
      title: "使用卡位",
      isAllCheck: [],
      telNumberListInit: [], //初始 可选的号码列表
      telNumberList: [], //可选的号码列表
      checkTelNumberList: [], //选择的号码列表
      telNumberShow: false,
      dialogVisible: false,
      loading: false,
      // totalPhoneNumber: 0,
      form: {
        orderSource: 1, //订单来源
        carrierId: 1,
        carrierName: "腾讯",
        chuzufangId: "",
        chuzufangName: "",
        zulinfangId: "",
        zulinfangName: "",
        num: "",
        monthNum: "",
        shifu: "",

        shiyongfei: "",
        fuwufei: "",
      },
      selectTenantInfo: "",
      queryParams: {
        pageSize: 10,
        pageNum: 1,
      },
      rules: {
        num: [
          { required: true, message: "请输入", trigger: "change" },
          { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
        ],
        monthNum: [
          { required: true, message: "请输入", trigger: "change" },
          { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
          { max: 120, message: "不能超过120", trigger: "blur" },
        ],
      },

      setObj: null,
      kexuanNum: 0,
      guanlifang: null,
      type: "add",
      orderInfo: null,
      fuwufeidanjia: 1,
    };
  },
  created() {},
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    // carrierTypes() {
    //   return this.$store.getters.gameYunyingshangList;
    // },
  },
  methods: {
    // 打开弹窗
    async open(type, item, setObj) {
      this.type = type;
      if (type == "add") {
        // 在共享市场下单
        this.guanlifang = item;
        this.setObj = setObj;
        console.log("%c Line:154 🍕 this.setObj", "color:#465975", this.setObj);
        this.form.carrierId = setObj.carrierId;
        this.form.carrierName = setObj.carrierName;
        this.form.num = "";
        this.form.monthNum = setObj.minMonth||'';
        this.form.zulinfangId = this.shopInfo.tenantId;
        this.form.zulinfangName = this.shopInfo.tenantName;
        this.form.chuzufangId = this.guanlifang.chuzufangId;
        this.form.chuzufangName = this.guanlifang.chuzufangName;
        this.dialogVisible = true;
        this.kexuanNum = item.cot;
      } else if (type == "xufei") {
        item;
        setObj
        console.log("%c Line:171 🍊 setObj", "color:#33a5ff", setObj);
        console.log("%c Line:149 🍣 item", "color:#465975", item);
        this.title = "卡位续费";
        this.orderInfo = item;
        this.dialogVisible = true;
        this.form.chuzufangName = item.chuzufangName;
        this.form.zulinfangId = item.zulinfangId;
        this.form.carrierName = item.carrierName;
        this.form.carrierId = item.carrierId;

       await this.getNumnowShareset(item.id);
      }
      await this.getFuwufeidanjia();

      this.jisuan()
      // this.form.telLeaseDetailsVos = [];
      // this.selectYYSType(1);
    },
    // 获取订单中有效号码数量和管理方的共享配置
    async getNumnowShareset(id) {
      const res = await phoneApi.getNumAndSetting({ id });
      if (res.data) {
        this.form.num = res.data.cot;
        if (this.getSetObj(res.data.settingsJson)) {
          this.setObj = this.getSetObj(res.data.settingsJson);
          this.form.monthNum = this.setObj.minMonth||'';
        }
      }
    },
    getSetObj(jsonstr) {
      let result = null;
      if (jsonstr) {
        const obj = JSON.parse(jsonstr);
        if (obj[this.form.carrierId]) {
          result = obj[this.form.carrierId];
        }
      }
      return result;
    },
    // 时长和数量改变
    jisuan() {
      this.form.num;
      this.form.monthNum;
      if (this.type!='xufei'&& this.form.num > this.kexuanNum) {
        this.form.num = this.kexuanNum;
        this.$message.error("号码数量不能超过库存数量！");
      }
      if (this.form.num && this.form.monthNum) {
        const zujin =
          this.form.num * this.form.monthNum * this.setObj.monthPrice;
        this.form.shiyongfei = zujin;
        this.form.fuwufei =
          this.form.num * this.form.monthNum * this.fuwufeidanjia;
        if (this.setObj.fuwufeiType == 2) {
          // 用户承担
          this.form.shifu = this.form.shiyongfei + this.form.fuwufei;
        } else {
          this.form.shifu = this.form.shiyongfei;
        }
      }
      // 计算到期时间
      if (this.form.monthNum && Number(this.form.monthNum)) {
        const result = new Date();
        result.setMonth(result.getMonth() + Number(this.form.monthNum));
        const r = this.parseTime(result, "{y}-{m}-{d}");
        this.form.expireTime = r;
      }
    },
    // 查询卡位服务费单价
    async getFuwufeidanjia() {
      const res = await this.getDicts("kaweifuwufei");
      if (res.data && res.data.length) {
        const obj = this.arrayToObject(res.data, "dictLabel");
        if (obj.kaweifuwufei && obj.kaweifuwufei.dictValue) {
          this.fuwufeidanjia = Number(obj.kaweifuwufei.dictValue);
        }
      }
    },

    // 重置
    reset() {
      this.$refs.form.resetFields();
    },

    submitForm() {
      // 表单校验
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.loading = true;
          // 判断是否低于起租月数
          if(this.setObj.minMonth&&Number(this.form.monthNum)<Number(this.setObj.minMonth)){
            return this.$message.error("使用时长不能低于"+this.setObj.minMonth+"个月！");
          }
          if (this.type == "xufei") {
            // 订单续费
            // 二次确认，提示将从余额支付
            this.$confirm(
              `当前共享订单实付${this.form.shifu}元将使用您的余额支付，确认支付吗？`,
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                const obj = {
                  renewalType: 1,
                  id: this.orderInfo.id,
                  monthNum: this.form.monthNum,
                  shifu: this.form.shifu,
                };
                phoneApi
                  .telShareOrderRenewal(obj)
                  .then((res) => {
                    this.loading = false;
                    this.$message.success(res.msg);
                    this.dialogVisible = false;
                    this.$emit("saved");
                    this.$store.dispatch("getShopInfo");
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              })
              .catch(() => {});
          } else {
            if (this.form.num > this.kexuanNum) {
              return this.$message.error("号码数量不能超过库存数量！");
            }
            // 二次确认，提示将从余额支付
            this.$confirm(
              `当前共享订单实付${this.form.shifu}元将使用您的余额支付，确认支付吗？`,
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                phoneApi
                  .telShareOrderPay(this.form)
                  .then((res) => {
                    this.loading = false;
                    this.$message.success(res.msg);
                    this.dialogVisible = false;
                    this.$parent.getList();
                    this.$store.dispatch("getShopInfo");
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              })
              .catch(() => {});
          }
        } else {
        }
      });
    },
    close() {
      this.resetForm("form");
      this.form.shiyongfei = "";
      this.form.fuwufei = "";
      this.form.shifu = "";
      this.dialogVisible = false;
    },

    close2() {
      this.telNumberShow = false;
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-radio input[aria-hidden="true"] {
  display: none !important;
}
.tip {
  color: #999;
  margin-top: 10px;
}
.price-box {
  color: #999;
  padding: 10px;
  border-radius: 8px;
  background-color: #f8f8f8;
  min-height: 50px;
  &.yue {
    height: 36px;
    margin-top: 10px;
  }
  // margin-top: 10px;
  > div {
    margin-right: 15px;
  }
  .price1 {
    color: #666;
    line-height: 26px;
    // font-size: 18px;
  }
  .price {
    font-size: 26px;
    color: red;
  }
}
.red {
  color: red;
}
</style>
